/**
 * SpaceIconSelector 组件
 *
 * 现代化的空间图标选择器，提供：
 * - 分类浏览图标
 * - 实时搜索功能
 * - 响应式网格布局
 * - 键盘导航支持
 * - 选中状态管理
 *
 * @example
 * ```tsx
 * <SpaceIconSelector
 *   selectedIconId="folder"
 *   onIconSelect={(iconId) => console.debug('Selected:', iconId)}
 *   onClose={() => setIsOpen(false)}
 * />
 * ```
 */

import React, { useState, useMemo, useCallback } from 'react';
import { Search, X } from 'lucide-react';
import { spaceIconCategories, searchSpaceIcons, type SpaceIconItem } from '@/lib/spaceIcons';
import { SpaceIcon } from './SpaceIcon';
import { Tooltip } from './Tooltip';
import { cn } from '@/lib/utils';
import { ScrollContainer } from '@/components/ui/ScrollContainer';

// SpaceIconSelector 组件 Props 接口
interface SpaceIconSelectorProps {
    // 当前选中的图标ID
    selectedIconId?: string;
    // 图标选择回调函数
    onIconSelect: (iconId: string) => void;
    // 关闭选择器回调函数
    onClose?: () => void;
    // 是否显示关闭按钮
    showCloseButton?: boolean;
    // 自定义容器类名
    className?: string;
}

/**
 * SpaceIconSelector 组件实现
 */
export const SpaceIconSelector: React.FC<SpaceIconSelectorProps> = ({
    selectedIconId = '',
    onIconSelect,
    onClose,
    showCloseButton = true,
    className = ''
}) => {
    // 搜索关键词状态
    const [searchQuery, setSearchQuery] = useState('');
    // 当前活跃的分类ID
    const [activeCategoryId, setActiveCategoryId] = useState('work');

    // 使用 useMemo 缓存搜索结果，避免重复计算
    const searchResults = useMemo(() => {
        return searchQuery.trim() ? searchSpaceIcons(searchQuery) : [];
    }, [searchQuery]);

    // 使用 useMemo 缓存当前分类的图标列表
    const currentCategoryIcons = useMemo(() => {
        const category = spaceIconCategories.find(cat => cat.id === activeCategoryId);
        return category?.icons || [];
    }, [activeCategoryId]);

    // 确定要显示的图标列表（搜索结果或分类图标）
    const displayedIcons = searchQuery.trim() ? searchResults : currentCategoryIcons;

    // 使用 useCallback 优化搜索处理函数
    const handleSearchChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
        setSearchQuery(e.target.value);
    }, []);

    // 使用 useCallback 优化图标选择处理函数
    const handleIconSelect = useCallback((iconId: string) => {
        onIconSelect(iconId);
    }, [onIconSelect]);

    // 使用 useCallback 优化分类切换处理函数
    const handleCategoryChange = useCallback((categoryId: string) => {
        setActiveCategoryId(categoryId);
        // 切换分类时清空搜索
        setSearchQuery('');
    }, []);

    // 使用 useCallback 优化清空搜索处理函数
    const handleClearSearch = useCallback(() => {
        setSearchQuery('');
    }, []);

    return (
        <div
            className={cn(
                // 固定宽度 + 视口自适应高度
                'bg-white border border-gray-200 rounded-lg shadow-lg p-4 w-[560px] md:w-[600px] max-w-full',
                'flex flex-col overflow-hidden',
                className,
            )}
        >
            {/* 头部区域：标题和关闭按钮 */}
            <div className="flex items-center justify-between mb-4 shrink-0">
                <h3 className="text-lg font-medium text-gray-900">选择图标</h3>
                {showCloseButton && onClose && (
                    <button
                        onClick={onClose}
                        className="p-1 rounded-md hover:bg-gray-100 transition-colors"
                        aria-label="关闭图标选择器"
                    >
                        <X size={20} className="text-gray-500" />
                    </button>
                )}
            </div>

            {/* 顶部搜索框：固定，下面左右两列独立滚动 */}
            <div className="relative mb-4 shrink-0">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Search size={16} className="text-gray-400" />
                </div>
                <input
                    type="text"
                    value={searchQuery}
                    onChange={handleSearchChange}
                    placeholder="搜索图标..."
                    className="block w-full pl-10 pr-10 py-2 border border-gray-300 rounded-md text-sm placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
                {searchQuery && (
                    <button
                        onClick={handleClearSearch}
                        className="absolute inset-y-0 right-0 pr-3 flex items-center"
                        aria-label="清空搜索"
                    >
                        <X size={16} className="text-gray-400 hover:text-gray-600" />
                    </button>
                )}
            </div>

            {/* 主体区域：左列分类（独立滚动） + 右侧图标（独立滚动） */}
            <div className="flex gap-4 flex-1 min-h-0">
                {/* 左侧分类列：独立滚动，固定较窄宽度；搜索时隐藏 */}
                {!searchQuery.trim() && (
                <nav className="w-32 shrink-0 pr-3 border-r border-gray-100" aria-label="图标分类">
                    <div className="h-full min-h-0">
                    <ScrollContainer className="h-full">
                        <ul className="space-y-2">
                            {spaceIconCategories.map((category) => (
                                <li key={category.id}>
                                    <button
                                        type="button"
                                        onClick={() => handleCategoryChange(category.id)}
                                        className={cn(
                                            'w-full text-center px-3 py-2 rounded-md text-sm transition-colors',
                                            activeCategoryId === category.id
                                                ? 'bg-blue-100 text-blue-700 border border-blue-200'
                                                : 'bg-gray-50 text-gray-700 hover:bg-gray-200 border border-transparent'
                                        )}
                                    >
                                        {category.name}
                                    </button>
                                </li>
                            ))}
                        </ul>
                    </ScrollContainer>
                    </div>
                </nav>
                )}

                {/* 右侧图标区域：独立滚动 */}
                <section className="flex-1 min-w-0 flex flex-col min-h-0">
                    <div className="flex-1 min-h-0">
                    <ScrollContainer className="h-full">
                        {displayedIcons.length > 0 ? (
                            <>
                                {searchQuery.trim() && (
                                    <div className="text-sm text-gray-500 mb-3">找到 {displayedIcons.length} 个图标</div>
                                )}
                                <div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(56px,1fr))] justify-items-center">
                                    {displayedIcons.map((icon) => (
                                        <IconGridItem
                                            key={icon.id}
                                            icon={icon}
                                            isSelected={icon.id === selectedIconId}
                                            onClick={() => handleIconSelect(icon.id)}
                                        />
                                    ))}
                                </div>
                            </>
                        ) : (
                            <div className="flex flex-col items-center justify-center py-12 text-center">
                                <Search size={48} className="text-gray-300 mb-3" />
                                <p className="text-gray-500 text-sm">
                                    {searchQuery.trim() ? '没有找到匹配的图标' : '选择分类查看图标'}
                                </p>
                                {searchQuery.trim() && (
                                    <button
                                        onClick={handleClearSearch}
                                        className="mt-2 text-blue-600 hover:text-blue-700 text-sm"
                                    >
                                        清空搜索条件
                                    </button>
                                )}
                            </div>
                        )}
                    </ScrollContainer>
                    </div>
                </section>
            </div>
        </div>
    );
};

/**
 * IconGridItem 组件
 *
 * 图标网格中的单个图标项组件
 */
interface IconGridItemProps {
    // 图标数据
    icon: SpaceIconItem;
    // 是否选中状态
    isSelected: boolean;
    // 点击回调函数
    onClick: () => void;
}

const IconGridItem: React.FC<IconGridItemProps> = React.memo(({
    icon,
    isSelected,
    onClick
}) => {
    return (
        <Tooltip
            content={`${icon.name} - ${icon.description}`}
            variant="info"
            side="bottom"
        >
            <button
                onClick={onClick}
                className={cn(
                    'flex items-center justify-center w-12 h-12 rounded-md border-2 transition-all duration-200',
                    'hover:border-blue-300 hover:bg-blue-50',
                    'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2',
                    isSelected
                        ? 'border-blue-500 bg-blue-100 shadow-md'
                        : 'border-gray-200 bg-white hover:shadow-sm'
                )}
                aria-label={`选择图标: ${icon.name}`}
            >
                <SpaceIcon
                    iconId={icon.id}
                    size={20}
                    className={cn(
                        'transition-colors',
                        isSelected ? 'text-blue-600' : 'text-gray-600'
                    )}
                />
            </button>
        </Tooltip>
    );
});

// 设置组件显示名称（用于React DevTools）
IconGridItem.displayName = 'IconGridItem';
